<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8"/>
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <title>作业管理</title>
    <link href="/assets/images/favicon.ico" rel="icon">
    <link rel="stylesheet" href="/assets/libs/layui/css/layui.css"/>
    <link rel="stylesheet" href="/assets/module/admin.css?v=318"/>

    <!--[if lt IE 9]>
    <script src="https://oss.maxcdn.com/html5shiv/3.7.3/html5shiv.min.js"></script>
    <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
    <![endif]-->
    <script type="text/javascript" src="/assets/libs/layui/layui.js"></script>
    <script type="text/javascript" src="/assets/js/common.js?v=318"></script>
    <style>
        /* 搜索栏样式 */
        .search-bar {
            padding: 10px;
            display: flex;
        }
        .layui-form-item .layui-inline {
            margin-bottom: 10px;
        }
        .layui-table-page {
            position: relative;
            /* 可根据需要调整上边距 */
        }
        .layui-table-box {
            margin-bottom: 10px;
        }
        .layui-form-item .layui-inline {
            margin-bottom: 10px;
        }
        /* Added some margin and padding for better form spacing */
        .layui-form-item {
            margin-bottom: 15px;
        }
        .layui-form-label {
            width: 100px;
        }
        .layui-input-inline {
            width: 200px;
        }
        /* Adjust button container layout */
        .button-container {
            margin: 20px 0;
        }
        .layui-btn {
            margin-right: 15px;
        }
        .layui-card-body {
            /*padding: 30px;*/
            margin-top: 40px;
            padding-top: 10px;
        }
        .layui-table {
            width: 100%;
        }
    </style>
    <script type="text/javascript">
        var url = window.location.pathname.substring(1);
        var item = url.split("/");
        var C = item[0];
        var A = item[1];
        var cUrl = "/" + C;
    </script>
</head>
<body>
<div>
    <div class="layui-card">
        <div class="layui-card-header search-bar">
            <form class="layui-form">
                <div class="layui-form-item">
                    <!-- 项目选择 -->
                    <div class="layui-inline">
                        <label class="layui-form-label">项目</label>
                        <div class="layui-input-inline">
                            <select id="projectSelect" name="project" lay-filter="projectSelect">
                                <option value="">请选择项目</option>
                                <option
                                        th:each="item : ${projectNameList}"
                                        th:text="${item}"
                                        th:value="${item}">
                                </option>
                            </select>
                        </div>
                    </div>
                    <!-- 班级选择 -->
                    <div class="layui-inline">
                        <label class="layui-form-label">班级</label>
                        <div class="layui-input-inline">
                            <select id="classSelect" name="classs" lay-filter="classSelect">
                                <option value="">请选择班级</option>
                                <option
                                        th:each="item : ${classesNameList}"
                                        th:text="${item}"
                                        th:value="${item}">
                                </option>
                            </select>
                        </div>
                    </div>
                    <!-- 类型 -->
                    <div class="layui-inline">
                        <label class="layui-form-label">类型</label>
                        <div class="layui-input-inline">
                            <input id="tbType" type="text" name="homeworkType" placeholder="请输入类型" autocomplete="off" class="layui-input">
                        </div>
                    </div>
                    <!-- 按钮区域 -->
                    <div class="layui-inline">
                        <div class="layui-input-inline" style="width: auto;">
                            <button id="search" class="layui-btn" lay-submit="" lay-filter="searchForm">
                                <i class="layui-icon layui-icon-search"></i> 查询
                            </button>
                        </div>
                    </div>
                </div>
            </form>
        </div>

        <div class="layui-card-body">

            <div class="button-container">
                <button id="addHomework" class="layui-btn layui-btn-primary">
                    <i class="layui-icon layui-icon-add-1"></i> 发布作业
                </button>
                <button id="deleteHomework" class="layui-btn layui-btn-primary">
                    <i class="layui-icon layui-icon-add-1"></i> 删除作业
                </button>
            </div>
            <table class="layui-hide" id="tableList" lay-filter="tableList"></table>
            <div class="layui-table-page"></div> <!-- 将分页栏放置在这里 -->
            <script th:inline="none">
                layui.use(['table', 'form', 'layer', 'laydate', 'jquery'], function () {
                    var $ = layui.jquery;
                    var layer = layui.layer;
                    var form = layui.form;
                    var table = layui.table;
                    var laydate = layui.laydate;
                    var projectNameList = [];
                    var classesNameList = [];
                    var userName;
                    var isAdmin = false;
                    // 获取班主任或管理员名字和相关数据
                    $(document).ready(function () {
                        // 发起两个 AJAX 请求
                        var getName = $.ajax({
                            url: '/user/findUserName',
                            type: 'GET'
                        });

                        var getIsAdmin = $.ajax({
                            url: '/user/userIsAdmin',
                            type: 'POST'
                        });

                        // 等待两个请求都完成
                        $.when(getName, getIsAdmin).done(function (response1, response2) {
                            // 处理是否是管理员请求的响应
                            var data2 = response2[0];

                            if (data2.code === 0) {
                                if (data2.data){
                                    isAdmin = true;
                                }
                            }
                            //console.log("isAdmin:", isAdmin);

                            // 处理获取姓名请求的响应
                            var data1 = response1[0]; // jQuery 的 $.when() 返回的是数组格式
                            if (data1.code === 0) {
                                userName = data1.data;
                                console.log(userName);
                                loadlist();
                            } else {
                                console.log(data1.msg);
                            }

                            // 继续执行后续逻辑
                            form.on('select(classSelect)', function (data) {
                                console.log("班级监听");
                                var selectedClass = data.value;
                                console.log(selectedClass);
                                if (selectedClass) {
                                    loadProjectsByClass(selectedClass);
                                } else {
                                    loadlist();
                                }
                            });
                        }).fail(function (xhr, status, error) {
                            console.error("请求失败: " + status + ", " + error);
                        });
                    });
                    //加载班主任或管理员对应的项目和班级列表
                    function  loadlist(){
                        $.ajax({
                            url: isAdmin?'/project/listProjectName':('/class/listChargerRelevance?param=project&chargerName=' + userName), // 查找班主任或管理员对应的项目
                            type: 'GET',
                            success: function (data) {
                                if (data && data.code === 0 && Array.isArray(data.data)) {
                                    projectNameList = data.data;
                                    var projectSelect = $('#projectSelect');
                                    projectSelect.empty();
                                    projectSelect.append('<option value="">请选择项目</option>');
                                    projectNameList.forEach(function (item) {
                                        projectSelect.append('<option value="' + item + '">' + item + '</option>');
                                    });
                                    form.render('select');
                                }
                            },
                            error: function (xhr, status, error) {
                                console.error("请求失败: " + status + ", " + error);
                            }
                        }),
                            $.ajax({
                                url: isAdmin?'/class/listClassName':('/class/listChargerRelevance?param=class&chargerName=' + userName), // 查找班主任对应的班级
                                type: 'GET',
                                success: function (data) {
                                    if (data && data.code === 0 && Array.isArray(data.data)) {
                                        classesNameList = data.data;
                                        var classSelect = $('#classSelect');
                                        classSelect.empty();
                                        classSelect.append('<option value="">请选择班级</option>');
                                        classesNameList.forEach(function (item) {
                                            classSelect.append('<option value="' + item + '">' + item + '</option>');
                                        });
                                        form.render('select');
                                    }
                                },
                                error: function (xhr, status, error) {
                                    console.error("请求失败: " + status + ", " + error);
                                }
                            })
                    }
                    function loadProjectsByClass(className) {
                        $.ajax({
                            url: '/class/getProjectsByClass', // 根据班级获取项目
                            type: 'GET',
                            data: { class: className },
                            success: function (data) {
                                if (data && data.code === 0 && Array.isArray(data.data)) {
                                    var projectSelect = $('#projectSelect');
                                    projectSelect.empty();
                                    data.data.forEach(function (item) {
                                        projectSelect.append('<option value="' + item + '">' + item + '</option>');
                                    });
                                    form.render('select');
                                }
                            },
                            error: function (xhr, status, error) {
                                console.error("请求失败: " + status + ", " + error);
                            }
                        });
                    }
                    table.render({
                        elem: '#tableList',
                        url: '/homework/list',
                        defaultToolbar: ['filter', 'exports', 'print', {
                            title: '提示',
                            layEvent: 'LAYTABLE_TIPS',
                            icon: 'layui-icon-tips'
                        }],
                        title: '作业数据',
                        cols: [[
                            {type: 'checkbox', width: 50},
                            {title: '序号', width: 60, templet: function (d) { return d.LAY_TABLE_INDEX + 1; }},
                            {
                                title: '班级', width: 100, templet: function (d) {
                                    return d.classs.className;
                                }
                            },
                            {
                                title: '项目名称', width: 150, templet: function (d) {
                                    return d.project.projectName;
                                }
                            },
                            {field: 'homeworkType', title: '作业类型', width: 100},
                            {field: 'title', title: '题目要求', width: 200},
                            {field: 'beginDate', title: '开始时间', width: 180, templet: function(d) {
                                    return formatDate(d.beginDate);
                                }},
                            {field: 'endDate', title: '结束时间', width: 180, templet: function(d) {
                                    return formatDate(d.endDate);
                                }},
                            {field: 'studentNum', title: '学员人数', width: 100},
                            {field: 'overNum', title: '批阅人数', width: 100},
                            {field: 'submitNum', title: '提交人数', width: 100},
                        ]],
                        page: true,
                        limit: 10,
                        limits: [10,50, 100, 150, 200],
                        id: 'tableList',
                        done: function (res, curr, count) {
                            // 打印后台返回的数据
                            console.log("返回的数据：", res.data);
                            $('.layui-table').css("width", "100%");
                            $("th[data-field='delete']").css("border-right", 'none');
                        }
                    });

                    $('#addHomework').click(function () {
                        window.ClassNames = classesNameList;
                        window.ProjectNames = projectNameList;
                        window.chargerName=userName;
                        layer.open({
                            type: 2,
                            title: '新增',
                            fixed: false,
                            maxmin: true,
                            area: ['80%', '80%'],
                            content: '/homework/form?id=0',
                            // offset:'50px'
                        })
                    });
                    // 格式化日期函数
                    function formatDate(dateStr) {
                        var date = new Date(dateStr);
                        var year = date.getFullYear();
                        var month = (date.getMonth() + 1).toString().padStart(2, '0');
                        var day = date.getDate().toString().padStart(2, '0');
                        var hour = date.getHours().toString().padStart(2, '0');
                        var minute = date.getMinutes().toString().padStart(2, '0');
                        var second = date.getSeconds().toString().padStart(2, '0');
                        return `${year}-${month}-${day} ${hour}:${minute}:${second}`;
                    }
                    $('#search').click(function () {
                        console.log('点击查询按钮');
                        var project = $('#projectSelect').val();
                        var className = $('#classSelect').val();
                        var homeworkType = $('#tbType').val();

                        console.log(project);
                        console.log(className);


                        // 确保在调用 reload 前有足够的时间处理用户输入
                        setTimeout(function () {
                            table.reload('tableList', {
                                url: '/homework/list',
                                method: 'post',
                                where: {
                                    project: $('#projectSelect').val(),
                                    classs: $('#classSelect').val(),
                                    homeworkType: $('#tbType').val()
                                },
                                page: {
                                    curr: 1 // 从第一页开始
                                },
                            });
                            console.log("查询完成");
                        }, 100); // 设置合理的延迟时间
                    });

                    // 批量删除作业
                    $('#deleteHomework').click(function () {
                        var checkStatus = table.checkStatus('tableList');
                        var data = checkStatus.data;
                        if (data.length === 0) {
                            layer.msg('请选择要删除的作业');
                            return;
                        }
                        var ids = data.map(function (item) {
                            return item.id; // 假设作业数据中包含id字段
                        });
                        layer.confirm('真的要删除选中的作业吗？', function (index) {
                            $.ajax({
                                type: 'POST',
                                dataType: 'json',
                                url: '/homework/deleteBatch',
                                data: {ids: ids},
                                traditional: true, // 防止深度序列化
                                success: function (response) {
                                    if (response.code == 0) {
                                        layer.msg('删除成功', {icon: 1});
                                        table.reload('tableList', {
                                            done: function (res, curr, count) {
                                                // 确保在删除和查询操作后执行以下代码
                                                $('.layui-table').css("width", "100%");
                                                $("th[data-field='delete']").css("border-right", 'none');
                                                // 检查当前页是否还有数据
                                                if (res.data.length === 0 && curr > 1) {
                                                    // 当前页没有数据且不是第一页，跳转到上一页
                                                    table.reload('tableList', {
                                                        page: {
                                                            curr: curr - 1
                                                        }
                                                    });
                                                }
                                            }
                                        });
                                    } else {
                                        layer.msg('删除成功', {icon: 1});
                                    }
                                }

                            });
                            layer.close(index);
                        });
                    });

                });
            </script>


        </div>
    </div>
</div>
</body>
</html>